#!/usr/bin/python

CONFIG_FILE = '../config.txt'
ACCOUNT = 0
DELAY = 0.1

import re
import sys
import time

sys.path.append('../')
import xmpp


def read_ConfigFile():
	"Read configuration settings for all accounts"
	global configs
	configs = {}
	for line in open(CONFIG_FILE).readlines():
		line = line.strip()
		if len(line) > 0 and not line.startswith('#'):	# Not a blank line or a comment
			key, value = line.split(':')
			key = key.strip().lower()
			value = value.strip()
			if configs.has_key(key):
				configs[key].append(value);
			else:
				configs[key] = [value]


def start_Connection(accIndex):
	domain = configs['domain'][accIndex]
	username = configs['username'][accIndex]
	password = configs['password'][accIndex]
	url = configs['url'][accIndex]
	port = int(configs['port'][accIndex])

	print 'ACTION: connecting %s@%s to server' % (username, domain)
	client = xmpp.Client(domain, debug=[])
	client.connect(server = (url, port))
	client.auth(username, password)
	client.sendInitPresence()
	return client


def save_Roster(bot, outputFile):
	counter = 1
	roster = bot.getRoster()
	contactsFile = open(outputFile, 'w')
	for JID in roster.getItems():
		line = '%s\t%s\n' % (JID, roster.getSubscription(JID))
		contactsFile.write(line)
		print counter, line,
		counter += 1
	contactsFile.close()


if __name__ == '__main__':
	read_ConfigFile()
	srcBot = start_Connection(ACCOUNT)
	save_Roster(srcBot, sys.argv[1])
